package com.yamaha.bikedesalon;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.json.JSONException;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.google.android.gcm.GCMRegistrar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.RequestParams;
import com.sromku.simple.fb.Permissions;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLoginListener;
import com.sromku.simple.fb.SimpleFacebookConfiguration;
import com.sromku.simple.fb.entities.Profile;
import com.yamaha.bikedesalon.util.API;
import com.yamaha.bikedesalon.util.SCStaticFunc;

public class LoginActivity extends Activity {
	private SimpleFacebook simpleFacebook;

	private static final AsyncHttpClient client = new AsyncHttpClient();
	private final String TAG = getClass().getSimpleName();
	private AsyncTask<Void, Void, Void> mRegisterTask;

	private final Permissions[] permissions = new Permissions[]{
			Permissions.EMAIL, Permissions.USER_ABOUT_ME,
			Permissions.USER_ACTIVITIES, Permissions.USER_BIRTHDAY,
			Permissions.USER_EDUCATION_HISTORY, Permissions.USER_GROUPS,
			Permissions.USER_HOMETOWN, Permissions.USER_INTERESTS,
			Permissions.USER_LIKES, Permissions.USER_LOCATION,
			Permissions.USER_SUBSCRIPTIONS, Permissions.USER_WEBSITE,
			Permissions.USER_WORK_HISTORY, Permissions.USER_STATUS,
			Permissions.READ_STREAM, Permissions.READ_FRIENDLISTS,
			Permissions.USER_PHOTOS, Permissions.FRIENDS_PHOTOS,
			Permissions.PUBLISH_ACTION};

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_login);
		showPackageInfo();

		simpleFacebook = SimpleFacebook.getInstance(this);
		simpleFacebook.logout(null);

		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(final View v) {
				signInWithFacebook();
			}
		});
	}

	private void showPackageInfo() {
		try {
			final PackageInfo info = getPackageManager().getPackageInfo("com.yamaha.bikdesalon", PackageManager.GET_SIGNATURES);
			for (final Signature signature : info.signatures) {
				final MessageDigest md = MessageDigest.getInstance("SHA");
				md.update(signature.toByteArray());
				final String s = Base64.encodeToString(md.digest(), Base64.DEFAULT);
				Log.d("YOURHASH KEY:", s);
			}

		} catch (final NameNotFoundException e) {

		} catch (final NoSuchAlgorithmException e) {

		}
	}

	private void signInWithFacebook() {

		Utils.showProgressDialog(this, "", "Logging in...");

		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setEnabled(false);

		final SimpleFacebookConfiguration configuration = new SimpleFacebookConfiguration.Builder().setAppId(getResources().getString(R.string.app_id)).setNamespace("yamaha_bikedesalon").setPermissions(permissions).build();

		SimpleFacebook.setConfiguration(configuration);

		final OnLoginListener onLoginListener = new SimpleFacebook.OnLoginListener() {

			@Override
			public void onFail(final String reason) {
				LogUtil.w("Facebook", reason);
				authButton.setEnabled(true);
			}

			@Override
			public void onException(final Throwable throwable) {
				LogUtil.e("Facebook", "Bad thing happened", throwable);
				authButton.setEnabled(true);
			}

			@Override
			public void onThinking() {
				// show progress bar or something to the user while login is
				// happening
				LogUtil.i("Facebook", "In progress");
			}

			@Override
			public void onLogin() {
				// change the state of the button or do whatever you want
				LogUtil.i("Facebook", "Logged in");
				handleGetFacebookInformation();
			}

			@Override
			public void onNotAcceptingPermissions() {
				LogUtil.w("Facebook", "User didn't accept read permissions");
				authButton.setEnabled(false);
			}

		};

		// login
		simpleFacebook.login(onLoginListener);
	}

	private void handleGetFacebookInformation() {
		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setEnabled(false);

		Utils.showProgressDialog(this, "", "Getting your Facebook Information");

		simpleFacebook.getProfile(new SimpleFacebook.OnProfileRequestListener() {

			@Override
			public void onFail(final String reason) {
				Utils.closeAllDialog();
				authButton.setEnabled(true);
				LogUtil.w("Facebook GetProfile", "Fail : " + reason);
			}

			@Override
			public void onException(final Throwable throwable) {
				Utils.closeAllDialog();
				authButton.setEnabled(true);
				LogUtil.e("Facebook GetProfile", "Bad thing happened", throwable);
			}

			@Override
			public void onThinking() {
				Utils.closeAllDialog();
				authButton.setEnabled(false);
				LogUtil.i("Facebook GetProfile", "In progress");
			}

			@Override
			public void onComplete(final Profile profile) {
				authButton.setEnabled(false);
				LogUtil.i("Facebook GetProfile", "Completed");
				final String id = profile.getId();
				LogUtil.i("Facebook GetProfile", "Id : " + id);
				LogUtil.i("Facebook GetProfile", "Name : " + profile.getName());
				LogUtil.i("Facebook GetProfile", "Email : " + profile.getEmail());

				SCStaticFunc.setUserId(LoginActivity.this, id);
				SCStaticFunc.setEmail(LoginActivity.this, profile.getEmail());
				// doRegisterPush(profile);
				doGetUserInfo(profile, "");
			}
		});

	}

	private void doRegisterPush(final Profile profile) {

		// if (!isRegisterd) {
		// isRegisterd = true;
		// registerReceiver(mHandleMessageReceiver, new IntentFilter(
		// DISPLAY_MESSAGE_ACTION));
		// }

		// Make sure the device has the proper dependencies.
		GCMRegistrar.checkDevice(this);

		// Make sure the manifest was properly set - comment out this line
		// while developing the app, then uncomment it when it's ready.
		GCMRegistrar.checkManifest(this);

		// Get GCM registration id
		final String regId = GCMRegistrar.getRegistrationId(this);

		// Check if regid already presents
		if (regId.equals("")) {
			// Registration is not present, register now with GCM
			LogUtil.i("Push Notification", "Reg Id Is Nothing.");
			GCMRegistrar.register(this, CommonUtilities.SENDER_ID);
			doGetUserInfo(profile, "");
		} else {
			// Device is already registered on GCM
			if (GCMRegistrar.isRegisteredOnServer(this)) {
				// Skips registration.
				doGetUserInfo(profile, regId);
			} else {
				// Try to register again, but not in the UI thread.
				// It's also necessary to cancel the thread onDestroy(),
				// hence the use of AsyncTask instead of a raw thread.
				final Context context = this;
				mRegisterTask = new AsyncTask<Void, Void, Void>() {

					@Override
					protected Void doInBackground(final Void... params) {
						// Register on our server
						// On server creates a new user
						LogUtil.i("Push Notification", "Get Reg Id : " + regId);
						doGetUserInfo(profile, regId);
						return null;
					}

					@Override
					protected void onPostExecute(final Void result) {
						mRegisterTask = null;
					}

				};
				mRegisterTask.execute(null, null, null);
			}
		}
	}

	private void doGetUserInfo(final Profile profile, final String regId) {
		final Button authButton = (Button) findViewById(R.id.auth_button);
		authButton.setEnabled(false);

		final RequestParams params = new RequestParams();
		params.put("user_id", profile.getId());
		params.put("email", profile.getEmail());
		params.put("firstname", profile.getFirstName());
		params.put("lastname", profile.getLastName());
		params.put("profile_image", "https://graph.facebook.com/" + profile.getId() + "/picture");
		params.put("at", simpleFacebook.getAccessToken());
		params.put("rid", regId);
		LogUtil.d("Get User Info", "Params : " + params.toString());

		client.post(API.GET_USERINFO, params, new MyAsyncHttpResponseHandler(API.GET_USERINFO, this) {

			@Override
			protected void onAsyncSuccess(final Object res)
					throws JSONException {
				Utils.closeAllDialog();

				SCStaticFunc.setUserInfo(LoginActivity.this, res.toString());

				// Utils.showToast(LoginActivity.this, "Logged in");

				finish();
				overridePendingTransition(0, 0);
				final Intent intent = new Intent(LoginActivity.this, MainActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		});
	}

	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		simpleFacebook.onActivityResult(this, requestCode, resultCode, data);
		super.onActivityResult(requestCode, resultCode, data);

	}
}
